<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\goods;

use app\common\model\Goods;
use app\common\model\GoodsContentManager;
use app\common\model\GoodsContentText;
use app\common\model\GoodsContentChapter;
use app\common\model\GoodsContentGroup;
use app\common\model\GoodsContentFile;
use think\facade\Db;

class ContentService
{
    /**
     * 获取商品付费内容
     * @param int $goodsId 商品ID
     * @param bool $hasAuth 是否有权限查看
     * @param int $userId 用户ID
     * @param bool $includeContent 是否包含章节内容（后台管理时设为false以提高性能）
     * @return array|null 处理后的内容数据
     */
    public function getGoodsPaidContent($goodsId, $hasAuth = false, $userId = 0, $includeContent = true)
    {
        $contentManager = GoodsContentManager::where('goods_id', $goodsId)->find();
        if (!$contentManager) {
            return null;
        }

        // 检查是否为免费内容(价格为0)
        $goods = Goods::find($goodsId);
        if ($goods && !$goods->price) {
            $hasAuth = true;  // 价格为0则自动有权限查看
        }

        // 根据类型返回不同结构的数据
        switch ($contentManager->type) {
            case 'text':
                // 从新的图文内容表获取数据
                $textContent = GoodsContentText::where('goods_id', $goodsId)->find();
                if (!$textContent) {
                    return [
                        'content' => ''
                    ];
                }
                // 根据图文内容收费类型判断是否有权限查看
                $textHasAuth = $hasAuth;
                if (!$textHasAuth && !$textContent->is_free) {
                    $textHasAuth = true;
                }
                return [
                    'content' => $textHasAuth ? $textContent->content : '需要购买后查看图文内容',
                ];

            case 'multi_chapter':
                $chapters = GoodsContentChapter::where('goods_id', $goodsId)
                    ->where('group_id', 0)  // 无分组的章节
                    ->order('sort asc, id asc')
                    ->select()
                    ->map(function ($chapter) use ($hasAuth, $goods, $includeContent) {
                        // 根据章节收费类型判断是否有权限查看
                        $chapterHasAuth = $hasAuth;
                        if (!$chapterHasAuth && !$chapter->is_free) {
                            $chapterHasAuth = true;
                        }

                        $chapterData = [
                            'id'            => $chapter->id,
                            'title'         => $chapter->title,
                            'is_free'       => $chapter->is_free,
                            'sort'          => $chapter->sort,
                            'resource_type' => $chapter->resource_type ?? 'text',
                            'create_time'   => $chapter->create_time
                        ];

                        // 只有在需要包含内容时才添加内容相关字段
                        if ($includeContent) {
                            // 处理长文本类型，从文件中读取内容
                            if ($chapter->resource_type == 'longtext') {
                                $textContentService     = new TextContentService();
                                $chapterData['content'] = $chapterHasAuth ?
                                    $textContentService->getChapterText($chapter->id, $chapter->goods_id, $goods->cate_id, true) :
                                    '需要购买后查看内容';
                            } else {
                                $chapterData['content'] = $chapterHasAuth ? $chapter->content : '需要购买后查看内容';
                            }

                            // 添加资源类型相关字段
                            if ($chapterHasAuth) {
                                $chapterData['video_url']      = $chapter->video_url ?? '';
                                $chapterData['video_duration'] = $chapter->video_duration ?? 0;
                                $chapterData['audio_url']      = $chapter->audio_url ?? '';
                                $chapterData['audio_duration'] = $chapter->audio_duration ?? 0;
                                $chapterData['cloud_url']      = $chapter->cloud_url ?? '';
                                $chapterData['cloud_password'] = $chapter->cloud_password ?? '';
                            }
                        }

                        return $chapterData;
                    })->toArray();

                return [
                    'chapters' => $chapters
                ];

            case 'chapter_groups':
                $groups = GoodsContentGroup::where('goods_id', $goodsId)
                    ->order('sort asc, id asc')
                    ->select()
                    ->map(function ($group) use ($hasAuth, $includeContent) {
                        $chapters = GoodsContentChapter::where('group_id', $group->id)
                            ->order('sort asc, id asc')
                            ->select()
                            ->map(function ($chapter) use ($hasAuth, $includeContent) {
                                // 根据章节收费类型判断是否有权限查看
                                $chapterHasAuth = $hasAuth;
                                if (!$chapterHasAuth && !$chapter->is_free) {
                                    $chapterHasAuth = true;
                                }

                                $chapterData = [
                                    'id'            => $chapter->id,
                                    'title'         => $chapter->title,
                                    'is_free'       => $chapter->is_free,
                                    'sort'          => $chapter->sort,
                                    'resource_type' => $chapter->resource_type ?? 'text',
                                    'create_time'   => $chapter->create_time
                                ];

                                // 只有在需要包含内容时才添加内容相关字段
                                if ($includeContent) {
                                    $chapterData['content'] = $chapterHasAuth ? $chapter->content : '需要购买后查看内容';
                                    // 添加资源类型相关字段
                                    if ($chapterHasAuth) {
                                        $chapterData['video_url']      = $chapter->video_url ?? '';
                                        $chapterData['video_duration'] = $chapter->video_duration ?? 0;
                                        $chapterData['audio_url']      = $chapter->audio_url ?? '';
                                        $chapterData['audio_duration'] = $chapter->audio_duration ?? 0;
                                        $chapterData['cloud_url']      = $chapter->cloud_url ?? '';
                                        $chapterData['cloud_password'] = $chapter->cloud_password ?? '';
                                    }
                                }

                                return $chapterData;
                            })->toArray();

                        return [
                            'id'       => $group->id,
                            'title'    => $group->title,
                            'chapters' => $chapters,
                            'is_free'  => $group->is_free,
                            'sort'     => $group->sort
                        ];
                    })->toArray();

                return $groups;

            case 'file':
                $file = GoodsContentFile::where('goods_id', $goodsId)->find();

                // 根据文件收费类型判断是否有权限查看
                $fileHasAuth = $hasAuth;
                if (!$fileHasAuth && $file) {
                    // 如果文件设置为免费，则有权限查看
                    if ($file->is_free) {
                        $fileHasAuth = true;
                    }

                    // 检查用户是否已登录
                    if (!$fileHasAuth && $userId) {
                        $user = \app\common\model\User::find($userId);
                        if ($user) {
                            // 检查用户是否为VIP且有权限
                            if ($user->isVip()) {
                                $fileHasAuth = true;
                            }
                        }
                    }
                }

                return [
                    'title'       => $file ? $file->title : '',
                    'description' => $file ? $file->description : '',
                    'file_url'    => $file ? ($fileHasAuth ? $file->file_url : '需要购买后获取下载链接') : '',
                    'file_size'   => $file ? $file->file_size : 0,
                ];

            case 'multi_file':
                $files = GoodsContentFile::where('goods_id', $goodsId)
                    ->order('sort asc, id asc')
                    ->select()
                    ->map(function ($file) use ($hasAuth, $goods, $userId) {
                        // 根据文件收费类型判断是否有权限查看
                        $fileHasAuth = $hasAuth;
                        if (!$fileHasAuth && $file->is_free) {
                            $fileHasAuth = true;
                        }
                        // 检查用户是否已登录
                        if (!$fileHasAuth && $userId) {
                            $user = \app\common\model\User::find($userId);
                            // 检查用户是否为VIP且有权限
                            if ($user->isVip()) {
                                $fileHasAuth = true;
                            }
                        }

                        return [
                            'id'          => $file->id,
                            'title'       => $file->title,
                            'description' => $file->description,
                            'file_url'    => $fileHasAuth ? $file->file_url : '需要购买后获取下载链接',
                            'file_size'   => $file->file_size,
                            'is_free'     => $file->is_free
                        ];
                    })->toArray();

                return [
                    'files' => $files
                ];

            default:
                return [
                    'content' => '未知内容类型'
                ];
        }
    }

    /**
     * 保存商品付费内容
     * @param int $goodsId 商品ID
     * @param string $type 内容类型
     * @param array $data 内容数据
     * @return bool
     */
    public function saveGoodsPaidContent($goodsId, $type, $data = [])
    {
        // 开始事务
        Db::startTrans();
        try {
            // 保存基本信息到内容管理器
            $contentManager = GoodsContentManager::where('goods_id', $goodsId)->find();
            if (!$contentManager) {
                $contentManager           = new GoodsContentManager;
                $contentManager->goods_id = $goodsId;
            }

            $contentManager->type = $type;
            // 保存内容管理器 附表分控器 发生在新增商品时
            $contentManager->save();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('保存付费内容失败：' . $e->getMessage());
        }
    }

    /**
     * 获取章节内容
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID，如果为0则从章节中获取
     * @param bool $hasAuth 是否有权限查看
     * @param int $userId 用户ID
     * @return array 章节内容
     */
    public function getChapterContent($chapterId, $goodsId = 0, $hasAuth = false, $userId = 0)
    {
        // 获取章节
        $chapter = GoodsContentChapter::find($chapterId);

        if (!$chapter) {
            throw new \Exception('章节不存在');
        }

        // 如果未提供商品ID，则从章节中获取
        if (!$goodsId) {
            $goodsId = $chapter->goods_id;
        }

        // 获取商品信息
        $goods = Goods::find($goodsId);

        // 检查章节收费类型
        $chapterHasAuth = $hasAuth;
        if (!$chapterHasAuth) {
            // 如果章节设置为免费，则有权限查看
            if ($chapter->is_free) {
                $chapterHasAuth = true;
            }
            // 如果章节设置为遵循商品价格，且商品价格为0，则有权限查看
            else if (!$chapter->is_free && $goods && !$goods->price) {
                $chapterHasAuth = true;
            }

            // 检查用户是否已登录
            if (!$chapterHasAuth && $userId) {
                $user = \app\common\model\User::find($userId);
                if ($user) {
                    // 检查用户是否为VIP且有权限
                    if ($user->isVip()) {
                        $chapterHasAuth = $user->canViewContent($chapterId);
                    }
                }
            }
        }

        // 获取上一章和下一章
        $prevChapter = GoodsContentChapter::where('goods_id', $goodsId)
            ->where('id', '<', $chapterId)
            ->order('sort desc, id desc')
            ->field('id, title')
            ->find();

        $nextChapter = GoodsContentChapter::where('goods_id', $goodsId)
            ->where('id', '>', $chapterId)
            ->order('sort asc, id asc')
            ->field('id, title')
            ->find();

        // 获取章节列表（用于目录）
        $chapterList = GoodsContentChapter::where('goods_id', $goodsId)
            ->field('id, title, is_free')
            ->order('sort asc, id asc')
            ->select();

        // 章节分组类型的特殊处理
        $contentManager = GoodsContentManager::where('goods_id', $chapter->goods_id)->find();
        $contentType    = $contentManager ? $contentManager->type : 'text';
        if ($contentType == 'chapter_groups') {
            // 获取章节内容
            $textContentService = new TextContentService();
            $chapter->content   = $hasAuth ? $textContentService->getChapterText($chapter->id, $chapter->goods_id, $goods->cate_id, true) : '';
        }
        return [
            'id'             => $chapter->id,
            'title'          => $chapter->title,
            'content'        => $chapterHasAuth ? $chapter->content : '需要购买后查看章节内容',
            'is_free'        => $chapter->is_free,
            'create_time'    => $chapter->create_time,
            // 资源类型相关字段
            'resource_type'  => $chapter->resource_type ?? 'text',
            'video_url'      => $chapterHasAuth ? ($chapter->video_url ?? '') : '',
            'video_duration' => $chapterHasAuth ? ($chapter->video_duration ?? 0) : 0,
            'audio_url'      => $chapterHasAuth ? ($chapter->audio_url ?? '') : '',
            'audio_duration' => $chapterHasAuth ? ($chapter->audio_duration ?? 0) : 0,
            'cloud_url'      => $chapterHasAuth ? ($chapter->cloud_url ?? '') : '',
            'cloud_password' => $chapterHasAuth ? ($chapter->cloud_password ?? '') : '',
            'prev_chapter'   => $prevChapter ? ['id' => $prevChapter->id, 'title' => $prevChapter->title] : null,
            'next_chapter'   => $nextChapter ? ['id' => $nextChapter->id, 'title' => $nextChapter->title] : null,
            'chapter_list'   => $chapterList,
            'has_auth'       => $chapterHasAuth,
            "goods"          => $goods
        ];
    }

    /**
     * 更新商品付费内容
     * @param int $goodsId 商品ID
     * @param string $paidContent 付费内容JSON字符串
     * @return bool
     */
    public function updateGoodsPaidContent($goodsId, $paidContent)
    {
        try {
            // 查找或创建商品内容管理记录
            $contentManager = GoodsContentManager::where('goods_id', $goodsId)->find();
            if (!$contentManager) {
                $contentManager           = new GoodsContentManager();
                $contentManager->goods_id = $goodsId;
                $contentManager->type     = 'text'; // 默认为图文类型
                $contentManager->save();
            }

            // 解析付费内容
            $contentData = json_decode($paidContent, true);
            if (!$contentData) {
                throw new \Exception('付费内容格式错误');
            }

            // 根据内容类型更新对应的表
            if ($contentManager->type === 'text') {
                // 更新图文内容表
                GoodsContentText::createOrUpdate($goodsId, [
                    'content' => $contentData['content'] ?? '',
                ]);
            }
            if ($contentManager->type === 'file') {
                // 更新文件内容表
                GoodsContentFile::createOrUpdateFile($goodsId, [
                    'file_url'    => $contentData['file_url'] ?? '',
                    'file_size'   => $contentData['file_size'] ?? 0,
                    'is_free'     => $contentData['is_free'] ?? 0,
                    'description' => $contentData['description'] ?? '',
                    'title'       => $contentData['title'] ?? '',
                ]);
            }
            if ($contentManager->type === 'multi_file') {
                // 更新文件内容表
                GoodsContentFile::createOrUpdate($goodsId, [
                    'file_url'    => $contentData['file_url'] ?? '',
                    'file_size'   => $contentData['file_size'] ?? 0,
                    'is_free'     => $contentData['is_free'] ?? 0,
                    'description' => $contentData['description'] ?? '',
                    'title'       => $contentData['title'] ?? '',
                ]);
            }

            $contentManager->save();

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 更新商品单文件内容
     * @param int $goodsId 商品ID
     * @param array $fileData 文件数据
     * @return bool 更新结果
     */
    public function updateGoodsFileContent($goodsId, $fileData)
    {
        try {
            // 开始事务
            Db::startTrans();

            // 查找或创建内容管理记录
            $contentManager = GoodsContentManager::where('goods_id', $goodsId)->find();
            if (!$contentManager) {
                $contentManager           = new GoodsContentManager();
                $contentManager->goods_id = $goodsId;
                $contentManager->type     = 'file';
                $contentManager->save();
            } else {
                // 更新内容类型为file
                $contentManager->type = 'file';
                $contentManager->save();
            }

            // 查找或创建文件记录
            $file = GoodsContentFile::where('goods_id', $goodsId)->find();
            if (!$file) {
                $file           = new GoodsContentFile();
                $file->goods_id = $goodsId;
            }

            // 更新文件信息
            $file->title       = $fileData['title'] ?? '';
            $file->description = $fileData['description'] ?? '';
            $file->file_url    = $fileData['file_url'] ?? '';
            $file->file_size   = $fileData['file_size'] ?? 0;
            $file->is_free     = $fileData['is_free'] ?? 0;
            $file->sort        = $fileData['sort'] ?? 0;
            $file->save();

            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception("更新文件内容失败: " . $e->getMessage());
        }
    }

    /**
     * 添加多文件内容中的单个文件
     * @param int $goodsId 商品ID
     * @param array $fileData 文件数据
     * @return bool 操作结果
     */
    public function addMultiFileItem($goodsId, $fileData)
    {
        try {
            // 开始事务
            Db::startTrans();

            // 查找或创建内容管理记录
            $contentManager = GoodsContentManager::where('goods_id', $goodsId)->find();
            if (!$contentManager) {
                $contentManager           = new GoodsContentManager();
                $contentManager->goods_id = $goodsId;
                $contentManager->type     = 'multi_file';
                $contentManager->save();
            } else if ($contentManager->type != 'multi_file') {
                // 更新内容类型为multi_file
                $contentManager->type = 'multi_file';
                $contentManager->save();
            }

            // 获取最大排序值
            $maxSort = GoodsContentFile::where('goods_id', $goodsId)->max('sort');
            $sort    = $maxSort !== null ? $maxSort + 1 : 0;

            // 添加文件记录
            $file              = new GoodsContentFile();
            $file->goods_id    = $goodsId;
            $file->title       = $fileData['title'] ?? '';
            $file->description = $fileData['description'] ?? '';
            $file->file_url    = $fileData['file_url'] ?? '';
            $file->file_size   = $fileData['file_size'] ?? 0;
            $file->is_free     = $fileData['is_free'] ?? 0;
            $file->sort        = $fileData['sort'] ?? $sort;
            $file->save();

            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception("添加文件失败: " . $e->getMessage());
        }
    }

    /**
     * 更新多文件内容中的单个文件
     * @param int $goodsId 商品ID
     * @param int $fileId 文件ID
     * @param array $fileData 文件数据
     * @return bool 操作结果
     */
    public function updateMultiFileItem($goodsId, $fileId, $fileData)
    {
        try {
            // 查找文件记录
            $file = GoodsContentFile::where('goods_id', $goodsId)
                ->where('id', $fileId)
                ->find();

            if (!$file) {
                throw new \Exception("文件不存在");
            }

            // 更新文件信息
            $file->title       = $fileData['title'] ?? $file->title;
            $file->description = $fileData['description'] ?? $file->description;
            $file->file_url    = $fileData['file_url'] ?? $file->file_url;
            $file->file_size   = $fileData['file_size'] ?? $file->file_size;
            $file->is_free     = $fileData['is_free'] ?? $file->is_free;
            $file->sort        = $fileData['sort'] ?? $file->sort;
            $file->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception("更新文件失败: " . $e->getMessage());
        }
    }

    /**
     * 删除多文件内容中的单个文件
     * @param int $goodsId 商品ID
     * @param int $fileId 文件ID
     * @return bool 操作结果
     */
    public function deleteMultiFileItem($goodsId, $fileId)
    {
        try {
            // 查找文件记录
            $file = GoodsContentFile::where('goods_id', $goodsId)
                ->where('id', $fileId)
                ->find();

            if (!$file) {
                throw new \Exception("文件不存在");
            }

            // 删除文件记录
            $file->delete();

            // 检查是否还有其他文件，如果没有则可能需要更改内容类型
            $fileCount = GoodsContentFile::where('goods_id', $goodsId)->count();
            if ($fileCount == 0) {
                // 可以选择将内容类型改为其他类型，或者保持不变
                // 这里我们选择保持不变
            }

            return true;
        } catch (\Exception $e) {
            throw new \Exception("删除文件失败: " . $e->getMessage());
        }
    }

    /**
     * 添加章节
     * @param array $data 章节数据
     * @return array 章节信息
     */
    public function addChapter($data)
    {
        Db::startTrans();
        try {
            // 确保商品内容管理记录存在
            $contentManager = GoodsContentManager::where('goods_id', $data['goods_id'])->find();
            if (!$contentManager) {
                $contentManager           = new GoodsContentManager();
                $contentManager->goods_id = $data['goods_id'];
                $contentManager->type     = 'multi_chapter';
                $contentManager->save();
            }

            // 创建章节
            $chapter           = new GoodsContentChapter();
            $chapter->goods_id = $data['goods_id'];
            $chapter->group_id = $data['group_id'] ?? 0;
            $chapter->title    = $data['title'];
            $chapter->content  = $data['content'] ?? '';
            $chapter->sort     = $data['sort'] ?? 0;
            $chapter->is_free  = $data['is_free'] ?? 0;

            // 保存资源类型相关字段
            $chapter->resource_type  = $data['resource_type'] ?? 'text';
            $chapter->video_url      = $data['video_url'] ?? '';
            $chapter->video_duration = $data['video_duration'] ?? 0;
            $chapter->audio_url      = $data['audio_url'] ?? '';
            $chapter->audio_duration = $data['audio_duration'] ?? 0;
            $chapter->cloud_url      = $data['cloud_url'] ?? '';
            $chapter->cloud_password = $data['cloud_password'] ?? '';

            $chapter->save();

            // 如果是长文本类型，将内容保存到文件中
            if ($chapter->resource_type == 'longtext') {
                // 获取商品信息以获取分类ID
                $goods = Goods::find($data['goods_id']);
                if ($goods) {
                    $textContentService = new TextContentService();
                    $textContentService->saveChapterText(
                        $chapter->id,
                        $chapter->goods_id,
                        $goods->cate_id,
                        $data['content'] ?? ''
                    );

                    // 长文本类型不需要在数据库中存储完整内容
                    $chapter->content = ''; // 内容已保存到文件中
                    $chapter->save();
                }
            }

            Db::commit();

            return $chapter->toArray();
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('添加章节失败：' . $e->getMessage());
        }
    }

    /**
     * 更新章节
     * @param int $chapterId 章节ID
     * @param array $data 章节数据
     * @return array 章节信息
     */
    public function updateChapter($chapterId, $data)
    {
        Db::startTrans();
        try {
            $chapter = GoodsContentChapter::find($chapterId);
            if (!$chapter) {
                throw new \Exception('章节不存在');
            }

            // 获取资源类型（使用传入的类型或保持原有类型）
            $resourceType = isset($data['resource_type']) ? $data['resource_type'] : ($chapter->resource_type ?? 'text');

            // 更新章节信息
            $chapter->title   = $data['title'];
            $chapter->sort    = $data['sort'] ?? $chapter->sort;
            $chapter->is_free = $data['is_free'] ?? $chapter->is_free;

            // 如果是更新为长文本类型或者已经是长文本类型
            if ($resourceType == 'longtext') {
                // 获取商品信息以获取分类ID
                $goods = Goods::find($chapter->goods_id);
                if ($goods && isset($data['content'])) {
                    $textContentService = new TextContentService();
                    $textContentService->saveChapterText(
                        $chapter->id,
                        $chapter->goods_id,
                        $goods->cate_id,
                        $data['content']
                    );

                    // 长文本类型不需要在数据库中存储完整内容
                    $chapter->content = ''; // 内容已保存到文件中
                }
            } else {
                // 普通文本类型，直接保存内容到数据库
                $chapter->content = $data['content'] ?? '';
            }

            // 更新资源类型相关字段
            $chapter->resource_type  = $resourceType;
            $chapter->video_url      = $data['video_url'] ?? '';
            $chapter->video_duration = $data['video_duration'] ?? 0;
            $chapter->audio_url      = $data['audio_url'] ?? '';
            $chapter->audio_duration = $data['audio_duration'] ?? 0;
            $chapter->cloud_url      = $data['cloud_url'] ?? '';
            $chapter->cloud_password = $data['cloud_password'] ?? '';

            $chapter->save();

            Db::commit();

            return $chapter->toArray();
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('更新章节失败：' . $e->getMessage());
        }
    }

    /**
     * 删除章节
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID（用于验证）
     * @return bool
     */
    public function deleteChapter($chapterId, $goodsId)
    {
        Db::startTrans();
        try {
            $chapter = GoodsContentChapter::find($chapterId);
            if (!$chapter) {
                throw new \Exception('章节不存在');
            }

            // 验证章节是否属于指定商品
            if ($chapter->goods_id != $goodsId) {
                throw new \Exception('章节不属于指定商品');
            }

            // 如果是长文本类型，删除对应的文本文件
            if ($chapter->resource_type == 'longtext') {
                $goods = Goods::find($goodsId);
                if ($goods) {
                    $textContentService = new TextContentService();
                    $textContentService->deleteChapterText($chapterId, $goodsId, $goods->cate_id);
                }
            }

            // 删除章节
            $chapter->delete();

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('删除章节失败：' . $e->getMessage());
        }
    }

    /**
     * 获取单个章节的完整信息（用于编辑）
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID（用于验证）
     * @return array|null
     */
    public function getChapterDetail($chapterId, $goodsId)
    {
        $chapter = GoodsContentChapter::find($chapterId);
        if (!$chapter) {
            return null;
        }

        // 验证章节是否属于指定商品
        if ($chapter->goods_id != $goodsId) {
            return null;
        }

        // 处理长文本类型，从文件中读取内容
        $content = $chapter->content;
        if ($chapter->resource_type == 'longtext') {
            $goods = Goods::find($goodsId);
            if ($goods) {
                $textContentService = new TextContentService();
                $content            = $textContentService->getChapterText($chapterId, $goodsId, $goods->cate_id, true);
            }
        }

        // 返回章节的完整信息
        return [
            'id'             => $chapter->id,
            'goods_id'       => $chapter->goods_id,
            'group_id'       => $chapter->group_id,
            'title'          => $chapter->title,
            'content'        => $content,
            'sort'           => $chapter->sort,
            'is_free'        => $chapter->is_free,
            'resource_type'  => $chapter->resource_type ?? 'text',
            'video_url'      => $chapter->video_url ?? '',
            'video_duration' => $chapter->video_duration ?? 0,
            'audio_url'      => $chapter->audio_url ?? '',
            'audio_duration' => $chapter->audio_duration ?? 0,
            'cloud_url'      => $chapter->cloud_url ?? '',
            'cloud_password' => $chapter->cloud_password ?? '',
            'create_time'    => $chapter->create_time,
            'update_time'    => $chapter->update_time,
        ];
    }
}